<script>
  import config from './config'
  import store from '@/store'
  import { getToken } from '@/utils/auth'
	import { appCheck } from "@/api/system/wechat"
  export default {
    onLaunch: function() {
      this.initApp()
	  if (uni.getSystemInfoSync().platform === 'android') {
	  	plus.runtime.getProperty(plus.runtime.appid, widgetInfo => {
	  		this.check(widgetInfo.versionCode, res => {
	  			this.downfile(res);
	  		})
	  	})
	  }
    },
    methods: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        if (!getToken()) {
          this.$tab.reLaunch('/pages/login') 
        }
      },
	  check: function(vers, call) {
	  	appCheck({
	  		"version": vers
	  	}).then(res => {
	  		if (res.code === 200 && res.data && res.data.version !== vers) {
				console.log('版本检查响应:', res.data)
	  			uni.showModal({
	  				title: '发现新版本',
	  				confirmText: '立即更新',
	  				cancelText: '下次更新',
	  				content: res.data.remark,
	  				showCancel: true,
	  				success: res1 => {
	  					if (res1.confirm) {
	  						this.downfile(1, res.data)
	  					}
	  				}
	  			});
	  		} 
	  	}).catch(err => {
			console.error('版本检查错误:', err)
			uni.showToast({
				title: '检查更新失败',
				icon: 'none'
			})
		});
	  },
	  downfile: function(da, data) {
		console.log('开始下载，参数:', {da, data})
	  	if (da === 1 && data && data.url) {
	  		var dtask = plus.downloader.createDownload(data.url, {},
	  			function(d, status) {
	  				uni.showToast({
	  					title: '下载完成',
	  					mask: false,
	  					duration: 1000
	  				});
	  				// 下载完成
	  				if (status == 200) {
	  					plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {},
	  						e => e,
	  						function(error) {
	  							uni.showToast({
	  								title: '安装失败-01',
	  								mask: false,
	  								duration: 1500
	  							});
	  						})
	  				} else {
	  					uni.showToast({
	  						title: '更新失败-02',
	  						mask: false,
	  						duration: 1500
	  					});
	  				}
	  			});
	  
	  		try {
	  			dtask.start(); // 开启下载的任务
	  			var prg = 0;
	  			var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 
	  			dtask.addEventListener('statechanged', function(
	  				task,
	  				status
	  			) {
	  				// 给下载任务设置一个监听 并根据状态  做操作
	  				switch (task.state) {
	  					case 1:
	  						showLoading.setTitle("正在下载");
	  						break;
	  					case 2:
	  						showLoading.setTitle("已连接到服务器");
	  						break;
	  					case 3:
	  						console.log('总共' +task.totalSize);
	  						console.log('总共' +JSON.stringify(task));
	  						var prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100);
	  						var prg2 = parseInt((parseFloat(task.totalSize) /
	  							1048576));
	  						showLoading.setTitle("正在下载" + prg + "% 共"+prg2+"M");
	  						break;
	  					case 4:
	  						plus.nativeUI.closeWaiting();
	  						//下载完成
	  						break;
	  				}
	  			});
	  		} catch (err) {
	  
	  			plus.nativeUI.closeWaiting();
	  			uni.showToast({
	  				title: '更新失败-03',
	  				mask: false,
	  				duration: 1500
	  			});
	  		}
	  
	  	}
	  }
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss';
</style>
